package com.example.demo.hotel.controller;

import com.example.demo.hotel.DTO.UserDTO;
import com.example.demo.hotel.service.IUserService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Result;
import java.util.List;

@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "http://localhost:8080/", methods = {RequestMethod.GET, RequestMethod.POST})
public class UserController {
    private final IUserService userService;

    public UserController(IUserService userService) {
        this.userService = userService;
    }

    /**
     * getAll
     * @return
     */
    @GetMapping("/get")
    public List<UserDTO> getAllUsers() {
        return userService.getAllUsers();
    }

    /**
     * getByID
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    public UserDTO getUserById(@PathVariable Integer id) {
        return userService.getUserById(id);
    }

    /**
     * add
     * @param userDTO
     * @return
     */
    @PostMapping("/add")
    public UserDTO createUser(@RequestBody UserDTO userDTO) {
        return userService.createUser(userDTO);
    }

    /**
     * update
     * @param id
     * @param userDTO
     * @return
     */
    @PutMapping("/update/{id}")
    public UserDTO updateUser(@PathVariable Integer id, @RequestBody UserDTO userDTO) {
        return userService.updateUser(id, userDTO);
    }

    /**
     * delete
     * @param id
     */
    @DeleteMapping("/delete/{id}")
    public void deleteUser(@PathVariable Integer id) {
        userService.deleteUser(id);
    }


    /**
     * login
     * @param userDTO
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody UserDTO userDTO) {
        boolean isValidUser = userService.validateUser(userDTO.getAccount(), userDTO.getPassword());
        if (isValidUser) {
            return ResponseEntity.ok("success");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("error");
        }
    }


}
